package logic

import (
	"context"
	"github.com/pkg/errors"
	"im_sys/apps/im/immodels"
	"im_sys/pkg/constants"
	"im_sys/pkg/xerr"

	"im_sys/apps/im/rpc/im"
	"im_sys/apps/im/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PutConversationsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPutConversationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PutConversationsLogic {
	return &PutConversationsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 更新用户会话数据
func (l *PutConversationsLogic) PutConversations(in *im.PutConversationsReq) (*im.PutConversationsResp, error) {
	// todo: add your logic here and delete this line
	// 首先获取用户当前的会话集合(UserConversation)，这是用户视角的会话状态记录
	data, err := l.svcCtx.UserConversationModel.FindByUserId(l.ctx, in.UserId)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewDBErr(), "Find conversation list by user id failed: %v", err)
	}

	if data.ConversationList == nil {
		// 如果用户没有任何会话记录，则初始化一个空映射
		data.ConversationList = make(map[string]*immodels.Conversation)
	}

	// 传入要更新的内容（如新标记的已读消息）
	for cid, conv := range in.ConversationList {
		var oldTotal int // 用户已读消息量
		if data.ConversationList[cid] != nil {
			// 用户会话记录中已存在该会话，保存会话的已读消息量
			oldTotal = data.ConversationList[cid].Total
		}

		data.ConversationList[cid] = &immodels.Conversation{
			ConversationId: conv.ConversationId,
			ChatType:       constants.ChatType(conv.ChatType),
			IsShow:         conv.IsShow,
			Total:          oldTotal + int(conv.Total), // conv.Total: 本次新标记为已读的消息数，累加后得总已读消息数
			Seq:            conv.Seq,
		}

		_, err = l.svcCtx.UserConversationModel.Update(l.ctx, data)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewDBErr(), "Update conversation list failed: %v", err)
		}

	}
	return &im.PutConversationsResp{}, nil
}
